package com.family.gmall.product.service.impl;

import com.family.gmall.product.service.TestService;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: family
 * @Date: 2023/7/15 10:56
 * @Description:
 */
@Service
public class TestServiceImpl implements TestService {

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void testLock() {
        // 创建锁：
        String skuId = "25";
        String locKey = "lock:" + skuId;
        // 锁的是每个商品
        RLock lock = redissonClient.getLock(locKey);
        lock.lock(10, TimeUnit.SECONDS);
        // 业务逻辑代码
        // 获取数据
        String value = (String) this.redisTemplate.opsForValue().get("num");
        if (StringUtils.isEmpty(value)) {
            return;
        }
        int num = Integer.parseInt(value);
        this.redisTemplate.opsForValue().set("num", String.valueOf(++num));
        lock.unlock();
    }

    @Override
    public String readLock() {
        // 初始化读写锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readwriteLock");
        RLock rLock = readWriteLock.readLock(); // 获取读锁

        rLock.lock(10, TimeUnit.SECONDS); // 加10s锁

        String msg = (String) this.redisTemplate.opsForValue().get("msg");
        //rLock.unlock(); // 解锁
        return msg;
    }

    @Override
    public String writeLock() {
        RReadWriteLock readwriteLock = redissonClient.getReadWriteLock("readwriteLock");
        RLock rLock = readwriteLock.writeLock();
        rLock.lock(10, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("msg", UUID.randomUUID().toString());
        return "成功写入了内容。。。。。。";
    }
}
